import React, { createContext, useContext, useState, useEffect } from 'react';
import DoubaoAPI from '../services/DoubaoAPI';

// 创建聊天上下文
const ChatContext = createContext();

// 聊天上下文提供者
export const ChatProvider = ({ children }) => {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [userEmotion, setUserEmotion] = useState('neutral');
  const [doubaoAPI] = useState(new DoubaoAPI('your_api_key_here'));

  // 发送消息
  const sendMessage = async (message) => {
    if (!message.trim()) return;
    
    setIsLoading(true);
    setError(null);
    
    try {
      // 1. 先添加用户消息到对话
      setMessages(prev => [...prev, { text: message, sender: 'user' }]);
      
      // 2. 分析用户情感
      const emotionAnalysis = await doubaoAPI.analyzeEmotion(message);
      if (emotionAnalysis.success) {
        setUserEmotion(emotionAnalysis.emotion);
      }
      
      // 3. 构建消息历史
      const messageHistory = messages.map(msg => ({
        role: msg.sender === 'user' ? 'user' : 'assistant',
        content: msg.text
      }));
      
      // 4. 添加系统消息
      messageHistory.unshift({
        role: 'system',
        content: `你是一个能够感知用户情感并给予相应回应的AI助手。当前用户情感状态：${userEmotion}`
      });
      
      // 5. 调用豆包API
      const response = await doubaoAPI.sendMessage(messageHistory);
      
      if (response.success) {
        // 6. 添加AI回复到对话
        const doubaoResponse = response.data.choices[0].message.content;
        const emotion = response.data.emotion || 'neutral';
        
        setMessages(prev => [...prev, { 
          text: doubaoResponse, 
          sender: 'doubao',
          emotion
        }]);
        
        // 7. 保存对话日志
        saveChatLog(message, doubaoResponse, emotion);
      } else {
        setError(response.error);
      }
    } catch (error) {
      console.error('Error sending message:', error);
      setError('发送消息失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 保存聊天日志
  const saveChatLog = async (userMessage, botMessage, emotion) => {
    try {
      // 实际应用中会调用后端API保存日志
      console.log('保存对话日志:', {
        timestamp: new Date().toISOString(),
        userMessage,
        botMessage,
        emotion
      });
      
      // 示例：
      // await fetch('/api/chat-logs', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({
      //     userMessage,
      //     botMessage,
      //     emotion
      //   })
      // });
      
    } catch (error) {
      console.error('Error saving chat log:', error);
    }
  };

  // 加载历史对话
  const loadChatHistory = async () => {
    try {
      // 实际应用中会从本地存储或后端加载历史对话
      console.log('加载历史对话');
      
      // 示例：
      // const response = await fetch('/api/chat-history');
      // const history = await response.json();
      // setMessages(history);
      
    } catch (error) {
      console.error('Error loading chat history:', error);
    }
  };

  // 初始化时加载历史对话
  useEffect(() => {
    loadChatHistory();
  }, []);

  const value = {
    messages,
    isLoading,
    error,
    userEmotion,
    sendMessage,
    setMessages
  };

  return (
    <ChatContext.Provider value={value}>
      {children}
    </ChatContext.Provider>
  );
};

// 自定义hook用于获取聊天上下文
export const useChat = () => {
  return useContext(ChatContext);
};    